﻿using NETCONLib;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Management;
using System.Net;
using System.Net.NetworkInformation;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace PSFChinaTelecom
{
    public partial class Form1 : Form
    {
        bool while_ = true;
        bool netstat = false;
        string[] known_gateways = new string[] { "10.3.0.1", "10.15.0.1" };
        string diaed_errors = "";
        string logg;

        public Form1()
        {
            InitializeComponent();
            CheckForIllegalCrossThreadCalls = false;
            new Thread(new ThreadStart(() =>
            {
                Thread.Sleep(1000);
                while (while_)
                {
                    try
                    {
                        string res = HttpGet("https://www.baidu.com");
                        if (res == null || res.IndexOf("百度") < 0)
                        {
                            stat.Text = "你的网络确实无法连接";
                            stat.ForeColor = Color.Red;
                            netstat = false;
                        }
                        else
                        {
                            stat.Text = "你的网络没问题，不用修复";
                            stat.ForeColor = Color.Green;
                            netstat = true;
                            Thread.Sleep(2000);
                        }
                    }
                    catch { }
                }
            })).Start();
            //检测网卡
            new Thread(new ThreadStart(() =>
            {
                Thread.Sleep(1000);
                while (while_)
                {
                    try
                    {
                        NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
                        NetworkInterface adapter_default;
                        int def_jps = int.MaxValue;
                        int active_ethernet = 0;
                        int active_wifi = 0;
                        int installed_wirednetcard = 0;
                        bool correct_connection = false;
                        bool dhcp_ok = true;
                        bool router_found = false;
                        string diae = "";
                        logg = "------PSF Debug------\n";
                        logg += label3.Text + " " + label4.Text + "\nMicrostorm - 保留所有权利。\n\n";
                        foreach (NetworkInterface adapter in nics)
                        {
                            //Wireless80211         无线网卡
                            //Ethernet              以太网卡
                            logg += "Collecting info for [" + adapter.Name + "]...";
                            switch (adapter.NetworkInterfaceType)
                            {
                                case NetworkInterfaceType.Wireless80211:
                                    {

                                        logg += "Wireless\n";
                                        if (adapter.OperationalStatus == OperationalStatus.Up)
                                        {
                                            active_wifi++;
                                            listerror.ForeColor = Color.Red;
                                            listerror.Text = "检测到一个连接的WIFI，请关掉它";
                                            diae += "WIFI_CONNECTED;";

                                            logg += "[WARNING] THIS ADAPTER MUST BE DISABLED.\n\n";
                                        }
                                        else
                                        {

                                            logg += "State = DOWN | Nothing to be done.\n\n";
                                        }
                                    }
                                    break;
                                case NetworkInterfaceType.Ethernet:
                                    {

                                        logg += "Wired\n";
                                        installed_wirednetcard++;
                                        if (adapter.OperationalStatus != OperationalStatus.Down)
                                        {
                                            active_ethernet++;
                                            IPInterfaceProperties ip = adapter.GetIPProperties();
                                            if (ip.GatewayAddresses.Count <= 0)
                                            {
                                                logg += "[WARNING] No gateway set.\n\n";
                                            }
                                            else
                                            {
                                                string gateway = ip.GatewayAddresses[0].Address.ToString();
                                                if (ip.DhcpServerAddresses.Count < 1)
                                                {
                                                    wrongrouter.ForeColor = Color.Orange;
                                                    dhcp_ok = false;
                                                    wrongrouter.Text = "DHCP不存在。手动IP无法诊断，请将IP设置调整到\"自动获取\"";
                                                    diae += "DHCP_NOT_EXSITS;";
                                                    logg += "[WARNING] DHCP down. It should be enabled.\n\n";
                                                }
                                                else
                                                if (known_gateways.Contains(gateway.ToString()))
                                                {
                                                    wrongrouter.ForeColor = Color.Green;
                                                    wrongrouter.Text = "您连接到了正确的接口";

                                                    logg += "Correct. | Nothing to be done.\n\n";
                                                    correct_connection = true;
                                                }
                                                else if (gateway.IndexOf("192.") > -1)
                                                {

                                                    logg += "[INFO] Self-host router. | MUST SET IT CORRECTLY.\n\n";
                                                    router_found = true;
                                                }
                                            }
                                        }
                                        else
                                        {
                                            logg += "State = DOWN | Nothing to be done.\n\n";
                                        }
                                    }
                                    break;
                                case NetworkInterfaceType.Loopback:
                                    logg += "Loopback\n\n";
                                    break;
                                default:
                                    logg += "Not-in-database\n\n";
                                    break;

                            }
                        }
                        if (!correct_connection && dhcp_ok)
                        {
                            if (router_found)
                            {
                                wrongrouter.ForeColor = Color.Orange;
                                wrongrouter.Text = "路由器设置可能不正确，请寻求人工协助";
                                diae += "SELF_HOST_ROUTER;";
                            }
                            else
                            if (urlAccessible("http://pre.go189.cn/"))
                            {
                                wrongrouter.ForeColor = Color.Orange;
                                wrongrouter.Text = "无法完成诊断，请寻求人工协助";
                                diae += "WRONG_ROUTER;PORTAL_ACCESSIBLE;";
                            }
                            else
                            {
                                wrongrouter.ForeColor = Color.Red;
                                wrongrouter.Text = "您使用的可能不是电信的接口 请使用墙上小盒子上的接口";
                                diae += "WRONG_ROUTER;";
                            }
                        }
                        if (active_ethernet > 1)
                        {
                            listerror.ForeColor = Color.Red;
                            listerror.Text = "您连接到不止一个网络(有wifi?)。断开其它连接。";
                            diae += "MORE_THAN_ONE_WIRED_ADAPTER;";
                        }
                        if (active_ethernet == 0)
                        {
                            plugerror.ForeColor = Color.Red;
                            plugerror.Text = "您使用的网线上没有信号。可能是网线没插好/损坏，或墙上接口损坏。可以试试舍友的接口。";
                            diae += "DEAD_PORT;";
                        }
                        else
                        if (active_ethernet > 0)
                        {
                            plugerror.ForeColor = Color.Green;
                            plugerror.Text = "网线和接口都不存在故障";
                        }
                        if (active_wifi == 0)
                        {
                            listerror.ForeColor = Color.Green;
                            listerror.Text = "您的可用网卡列表设置正确";
                        }
                        else
                        if (installed_wirednetcard < 1)
                        {
                            listerror.ForeColor = Color.Red;
                            listerror.Text = "您的电脑上没有找到网线接口，可能需要购买转换器。";
                            diae += "NO_WIRED_ADAPTER;";
                        }
                        if (!button1.Enabled)
                        {
                            log.Text = logg;
                            log.Text += "已收集所有必要信息。\n本框内的信息用于调试软件，需要人工协助时请点击[我的问题没有解决]。\n以上信息不能帮助技术人员完成网络诊断。";
                            this.log.SelectionStart = this.log.Text.Length;
                            this.log.ScrollToCaret();
                        }
                        diaed_errors = diae;
                        button1.Enabled = true;
                        label2.Text = "需要人工协助？点击右侧按钮然后把下方文字发给我→";
                        Thread.Sleep(1000);
                    }
                    catch (Exception e)
                    {
                    }
                }
            })).Start();
        }

        public bool urlAccessible(string url)
        {
            try
            {
                string res = HttpGet(url);
                if (res == null || res.Length < 10)
                {
                    return false;
                }
                else
                {
                    return true;
                }
            }
            catch
            {
                return false;
            }
        }

        public string HttpGet(string Url)
        {
            try
            {
                string retString = string.Empty;

                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
                request.Method = "GET";
                request.Timeout = 1000;
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream myResponseStream = response.GetResponseStream();
                StreamReader streamReader = new StreamReader(myResponseStream);
                retString = streamReader.ReadToEnd();
                streamReader.Close();
                myResponseStream.Close();
                return retString;
            }
            catch (Exception ex)
            {
                return null;
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
            NetworkInterface adapter_default;
            log.Text = "请将以下信息以文本形式发送给技术支持人员。这些信息可以帮助技术人员找到您互联网配置上存在的明显问题。\n这些信息包含您的设备唯一标识，请不要提供给不信任的人。\n\n";
            log.Text += "REPORT>" + diaed_errors + (netstat ? "NET_OK;" : "NET_DOWN;") + logg + "\n\n-----------COMMAND HOST--------------\n";
            log.Text += "COMMAND>ipconfig\n" + GetIPConfigReturns() + "\n\n\n";
            log.Text += "COMMAND>route print\n" + GetRouteReturns() + "\n\n\n";
            log.SelectAll();
            Clipboard.SetText(log.Text);
        }

        public static string GetIPConfigReturns()
        {
            string version = System.Environment.OSVersion.VersionString;

            if (version.Contains("Windows"))
            {
                //调用ipconfig ,并传入参数: /all
                System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo("ipconfig", "/all");

                psi.CreateNoWindow = true; //若为false，则会出现cmd的黑窗体
                psi.RedirectStandardOutput = true;
                psi.UseShellExecute = false;

                System.Diagnostics.Process p = System.Diagnostics.Process.Start(psi);

                return p.StandardOutput.ReadToEnd();
            }

            return string.Empty;
        }

        public static string GetRouteReturns()
        {
            string version = System.Environment.OSVersion.VersionString;

            if (version.Contains("Windows"))
            {
                //调用ipconfig ,并传入参数: /all
                System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo("route", "print");

                psi.CreateNoWindow = true; //若为false，则会出现cmd的黑窗体
                psi.RedirectStandardOutput = true;
                psi.UseShellExecute = false;

                System.Diagnostics.Process p = System.Diagnostics.Process.Start(psi);

                return p.StandardOutput.ReadToEnd();
            }

            return string.Empty;
        }

        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            while_ = false;
        }

        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            string log = "任务下发：重启所有网络适配器\n列适配器...";
            try
            {
                NetSharingManager manager = new NetSharingManager();
                INetSharingEveryConnectionCollection connections = manager.EnumEveryConnection;
                log += "Done\n";
                int done = 0;
                int dec = 0;
                foreach (INetConnection c in connections)
                {
                    try
                    {
                        var m = manager.NetConnectionProps[c];
                        log += "[" + m.Name + "]...Detected...";
                        dec++;
                        var sharing = manager.INetSharingConfigurationForINetConnection[c];
                        c.Disconnect();
                        log += "Disconnected...";
                        c.Connect();
                        log += "Connected.\n";
                        done++;
                    }
                    catch
                    {
                        log += "FAIL.\n";
                    }
                }
                log += "\n检测到" + dec + "个网络适配器，重连了" + done + "个。\n并非所有适配器都能被操作，这是正常的。\n\n请等待几秒，上方诊断信息将会刷新。";
            }
            catch (Exception err)
            {
                if (err.Message.IndexOf("拒绝访问") >= 0)
                {
                    log += "FAIL\n\n没有权限操作网络适配器。\n开启本程序时请右键，点击\"以管理员身份运行(A)\"来授权本程序进行高级操作。";
                }
                else
                {
                    log += "FAIL\n\n操作未能完成，下面的错误报告有助于找到问题：\n" + err.Message + "\n\nStackTrace:\n" + err.StackTrace;
                }
            }
            this.log.Text = log;
            this.log.SelectionStart = this.log.Text.Length;
            this.log.ScrollToCaret();
        }

        private void log_TextChanged(object sender, EventArgs e)
        {

        }
    }
}
